package com.kiss.rpc.serialize.impl;

import com.kiss.rpc.exceptions.SerializeException;
import com.kiss.rpc.serialize.Serializer;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

@Slf4j
public class JdkSerializer implements Serializer {

    @Override
    public byte[] serialize(Object obj){
        byte[] bytes;
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        try (ObjectOutputStream out = new ObjectOutputStream(buffer)) {
            out.writeObject(obj);
            out.flush();
            bytes = buffer.toByteArray();
            out.close();
            buffer.close();
            if (log.isDebugEnabled()) {
                log.debug("对输入的Object序列化，得到长度为【{}】的字节数组", bytes.length);
            }
            return bytes;
        }
        catch (IOException e) {
            log.error(e.getMessage());
            throw new SerializeException(e);
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        T obj;
        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
            obj = (T) in.readObject();
            return obj;
        }
        catch (IOException | ClassNotFoundException e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
